/**
 * 数据一致性测试组件
 * 用于验证缓存数据和解析数据的一致性
 */

import React, { useState } from 'react';
import { Card, Button, Space, Table, Alert, Descriptions, Tag, Divider } from 'antd';
import { CheckCircleOutlined, ExclamationCircleOutlined, ReloadOutlined } from '@ant-design/icons';
import { LineageService } from '../services/lineageService';

interface ConsistencyReport {
  cacheData: any;
  parseData: any;
  inconsistencies: string[];
  isConsistent: boolean;
}

const DataConsistencyTest: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [rebuilding, setRebuilding] = useState(false);
  const [report, setReport] = useState<ConsistencyReport | null>(null);

  const runConsistencyTest = async () => {
    setLoading(true);
    try {
      // 获取缓存数据
      const cacheResponse = await LineageService.getCachedLineageData();

      // 直接解析数据库生成新的血缘数据
      const parseResponse = await LineageService.parseDatabaseLineage();

      const cacheData = cacheResponse.data;
      const parseData = parseResponse.data;

      // 检查数据一致性
      const inconsistencies: string[] = [];

      if (cacheData && parseData) {
        // 比较任务数量
        const cacheTaskCount = cacheData.task_level_nodes?.length || 0;
        const parseTaskCount = parseData.task_level_nodes?.length || 0;
        if (cacheTaskCount !== parseTaskCount) {
          inconsistencies.push(`任务数量不一致: 缓存${cacheTaskCount} vs 解析${parseTaskCount}`);
        }

        // 比较任务级连接数量
        const cacheEdgeCount = cacheData.task_level_edges?.length || 0;
        const parseEdgeCount = parseData.task_level_edges?.length || 0;
        if (cacheEdgeCount !== parseEdgeCount) {
          inconsistencies.push(`任务连接数量不一致: 缓存${cacheEdgeCount} vs 解析${parseEdgeCount}`);
        }

        // 比较节点总数
        const cacheNodeCount = cacheData.nodes?.length || 0;
        const parseNodeCount = parseData.nodes?.length || 0;
        if (cacheNodeCount !== parseNodeCount) {
          inconsistencies.push(`节点总数不一致: 缓存${cacheNodeCount} vs 解析${parseNodeCount}`);
        }

        // 比较连接总数
        const cacheAllEdgeCount = cacheData.edges?.length || 0;
        const parseAllEdgeCount = parseData.edges?.length || 0;
        if (cacheAllEdgeCount !== parseAllEdgeCount) {
          inconsistencies.push(`连接总数不一致: 缓存${cacheAllEdgeCount} vs 解析${parseAllEdgeCount}`);
        }

        // 比较连接器数量
        const cacheConnectorCount = cacheData.connectors?.length || 0;
        const parseConnectorCount = parseData.connectors?.length || 0;
        if (cacheConnectorCount !== parseConnectorCount) {
          inconsistencies.push(`连接器数量不一致: 缓存${cacheConnectorCount} vs 解析${parseConnectorCount}`);
        }

        // 比较统计信息
        const cacheStats = cacheData.statistics || {};
        const parseStats = parseData.statistics || {};
        
        if (cacheStats.total_nodes !== parseStats.total_nodes) {
          inconsistencies.push(`统计-节点数不一致: 缓存${cacheStats.total_nodes} vs 解析${parseStats.total_nodes}`);
        }
        if (cacheStats.total_edges !== parseStats.total_edges) {
          inconsistencies.push(`统计-连接数不一致: 缓存${cacheStats.total_edges} vs 解析${parseStats.total_edges}`);
        }
        if (cacheStats.task_level_nodes !== parseStats.task_level_nodes) {
          inconsistencies.push(`统计-任务节点数不一致: 缓存${cacheStats.task_level_nodes} vs 解析${parseStats.task_level_nodes}`);
        }
        if (cacheStats.task_level_edges !== parseStats.task_level_edges) {
          inconsistencies.push(`统计-任务连接数不一致: 缓存${cacheStats.task_level_edges} vs 解析${parseStats.task_level_edges}`);
        }
      }

      setReport({
        cacheData,
        parseData,
        inconsistencies,
        isConsistent: inconsistencies.length === 0
      });

    } catch (error) {
      console.error('一致性测试失败:', error);
    } finally {
      setLoading(false);
    }
  };

  const rebuildCache = async () => {
    setRebuilding(true);
    try {
      const result = await LineageService.rebuildCache();

      if (result.success) {
        // 重建成功后重新运行测试
        await runConsistencyTest();
      } else {
        console.error('重建缓存失败:', result.message);
      }
    } catch (error) {
      console.error('重建缓存失败:', error);
    } finally {
      setRebuilding(false);
    }
  };



  const columns = [
    {
      title: '数据项',
      dataIndex: 'item',
      key: 'item',
    },
    {
      title: '缓存数据',
      dataIndex: 'cache',
      key: 'cache',
    },
    {
      title: '解析数据',
      dataIndex: 'parse',
      key: 'parse',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: boolean) => (
        status ? 
          <Tag color="green" icon={<CheckCircleOutlined />}>一致</Tag> :
          <Tag color="red" icon={<ExclamationCircleOutlined />}>不一致</Tag>
      )
    }
  ];

  const getComparisonData = () => {
    if (!report) return [];

    const { cacheData, parseData } = report;
    
    return [
      {
        key: '1',
        item: '任务数量',
        cache: cacheData?.task_level_nodes?.length || 0,
        parse: parseData?.task_level_nodes?.length || 0,
        status: (cacheData?.task_level_nodes?.length || 0) === (parseData?.task_level_nodes?.length || 0)
      },
      {
        key: '2',
        item: '任务连接',
        cache: cacheData?.task_level_edges?.length || 0,
        parse: parseData?.task_level_edges?.length || 0,
        status: (cacheData?.task_level_edges?.length || 0) === (parseData?.task_level_edges?.length || 0)
      },
      {
        key: '3',
        item: '节点总数',
        cache: cacheData?.nodes?.length || 0,
        parse: parseData?.nodes?.length || 0,
        status: (cacheData?.nodes?.length || 0) === (parseData?.nodes?.length || 0)
      },
      {
        key: '4',
        item: '连接总数',
        cache: cacheData?.edges?.length || 0,
        parse: parseData?.edges?.length || 0,
        status: (cacheData?.edges?.length || 0) === (parseData?.edges?.length || 0)
      },
      {
        key: '5',
        item: '连接器数量',
        cache: cacheData?.connectors?.length || 0,
        parse: parseData?.connectors?.length || 0,
        status: (cacheData?.connectors?.length || 0) === (parseData?.connectors?.length || 0)
      }
    ];
  };

  return (
    <Card title="数据一致性测试" extra={
      <Space>
        <Button
          type="primary"
          icon={<ReloadOutlined />}
          loading={loading}
          onClick={runConsistencyTest}
        >
          运行测试
        </Button>
        <Button
          type="default"
          danger
          loading={rebuilding}
          onClick={rebuildCache}
          disabled={loading}
        >
          重建缓存
        </Button>
      </Space>
    }>
      {report && (
        <>
          <Alert
            message={report.isConsistent ? "数据一致性检查通过" : "发现数据不一致"}
            type={report.isConsistent ? "success" : "error"}
            showIcon
            style={{ marginBottom: 16 }}
          />

          {!report.isConsistent && (
            <>
              <Alert
                message="不一致项目"
                description={
                  <ul>
                    {report.inconsistencies.map((item, index) => (
                      <li key={index}>{item}</li>
                    ))}
                  </ul>
                }
                type="warning"
                style={{ marginBottom: 16 }}
              />
            </>
          )}

          <Table
            columns={columns}
            dataSource={getComparisonData()}
            pagination={false}
            size="small"
          />

          <Divider />

          <Descriptions title="详细统计信息" column={2} size="small">
            <Descriptions.Item label="缓存数据源">
              {report.cacheData?.statistics?.last_update ? '数据库缓存' : '实时解析'}
            </Descriptions.Item>
            <Descriptions.Item label="解析数据源">
              实时解析
            </Descriptions.Item>
            <Descriptions.Item label="缓存更新时间">
              {report.cacheData?.statistics?.last_update || '未知'}
            </Descriptions.Item>
            <Descriptions.Item label="解析处理时间">
              {report.parseData?.processing_time?.toFixed(2) || 0}s
            </Descriptions.Item>
          </Descriptions>
        </>
      )}
    </Card>
  );
};

export default DataConsistencyTest;
